//
//  LCFloatingWindow.m
//  LC
//
//  Created by admin on 17/5/22.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "LCFloatingWindow.h"
#import "Masonry/Masonry.h"
#import "JKSongsMessStatus.h"

#import <zhPopupController/zhPopupController.h>
#import "zhWallView.h"
@interface LCFloatingWindow ()

@property (strong, nonatomic)   UIView  *contentView;

@property (strong, nonatomic) UIButton *playOrPauseButton;

@property (nonatomic,strong) UILabel *titleLabel;

@property (nonatomic,strong) UILabel *albumLabel;

@property (nonatomic,strong) UIImageView *titleImageView;

@property (nonatomic, strong) zhPopupController *zh_popupController; // 

@end

@implementation LCFloatingWindow

+ (LCFloatingWindow *)sharedInstance {
    static dispatch_once_t onceToken;
    
    static LCFloatingWindow *__instance__;
    dispatch_once(&onceToken, ^{
        __instance__ = [LCFloatingWindow new];
    });
    return __instance__;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        // 安装通知
        [self setupNotifications];

        // 添加到根视图中
        [[[UIApplication sharedApplication].delegate window] addSubview:self];
        
        self.backgroundColor = [UIColor whiteColor];
//        self.alpha = 0.9;
        [self mas_makeConstraints:^(MASConstraintMaker *make) {
            if (@available(iOS 11.0, *)) {
                make.bottom.equalTo([[UIApplication sharedApplication].delegate window].mas_safeAreaLayoutGuideBottom).offset(0);
            }else{
                make.bottom.offset(0);
            }
            make.left.offset(0);
            make.right.offset(0);
            make.height.offset(60);
        }];
        

        // 添加一个点击按钮
//        UIButton *tapButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        tapButton.backgroundColor = [UIColor clearColor];
//        [tapButton addTarget:self action:@selector(actionTap:) forControlEvents:UIControlEventTouchUpInside];
//        [self addSubview:tapButton];
//        [tapButton mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.edges.equalTo(self);
//        }];
        
        
        ///添加一个播放/停止
        UIButton *playOrPauseButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 200 * 9/16 - 80 , 100, 50)];
        _playOrPauseButton = playOrPauseButton;
        [playOrPauseButton setImage:[UIImage imageNamed:@"newPlay"] forState:UIControlStateNormal];
        [playOrPauseButton setImage:[UIImage imageNamed:@"newPause"] forState:UIControlStateSelected];


        playOrPauseButton.layer.borderColor = RGBColor(255, 255, 255).CGColor;
        playOrPauseButton.layer.borderWidth = 1;
        playOrPauseButton.layer.cornerRadius = 5;
        [playOrPauseButton addTarget:self action:@selector(actionPlayOrPause:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:playOrPauseButton];
        ///添加一个播放下一首
        UIButton *playNextButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 200 * 9/16 - 80 , 100, 50)];
        [playNextButton setImage:[UIImage imageNamed:@"newNext"] forState:UIControlStateNormal];
        playNextButton.layer.borderColor = RGBColor(255, 255, 255).CGColor;
        playNextButton.layer.borderWidth = 1;
        playNextButton.layer.cornerRadius = 5;
        [playNextButton addTarget:self action:@selector(actionNext:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:playNextButton];
        [playOrPauseButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.offset(0);
//            make.width.offset(60);
            make.width.equalTo(self.mas_height).offset(-18);
            make.right.equalTo(playNextButton.mas_left);
            make.height.equalTo(self);
        }];

        [playNextButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.offset(0);
//            make.width.offset(60);
            make.width.equalTo(self.mas_height).offset(-10);
            make.right.offset(0);
            make.height.equalTo(self);
        }];
        
        // 添加一个列表按钮
        UIButton *listButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [listButton setImage:[UIImage imageNamed:@"playerbar_list"] forState:UIControlStateNormal];
        [self addSubview:listButton];
        [listButton addTarget:self action:@selector(actionLiebiao:) forControlEvents:UIControlEventTouchUpInside];
        [listButton sizeToFit];
        [listButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self).offset(0);
            make.right.equalTo(playOrPauseButton.mas_left).offset(0);
            make.height.equalTo(self);
            make.width.equalTo(self.mas_height).offset(-10);
        }];
        // 歌曲名称
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 22, 100, 30)];
        _titleLabel = titleLabel;
        titleLabel.font = [UIFont systemFontOfSize:15];
        titleLabel.text = @"爱人如己,传播快乐";

        [self addSubview:titleLabel];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self).offset(0);
            make.left.equalTo(self).offset(80);
//            make.width.offset(150);
            make.right.equalTo(listButton.mas_left).offset(0);
            make.height.equalTo(@(40));
        }];

        
        UILabel *albumLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 22, 100, 30)];
        _albumLabel = albumLabel;
        albumLabel.font = [UIFont systemFontOfSize:12];
        albumLabel.text = @"";
        
        [self addSubview:albumLabel];
        
        [albumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self).offset(0);
            make.left.equalTo(self).offset(80);
            make.width.offset(120);
            make.height.equalTo(@(40));
        }];

        UIImageView *titleImageView = [[UIImageView alloc] init];
        _titleImageView = titleImageView;
        titleImageView.image = [UIImage imageNamed:@"play_icon"];
        [self addSubview:titleImageView];
        [titleImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self);
            make.left.equalTo(self).offset(20);
            make.width.offset(50);
            make.height.offset(50);
        }];
        UISlider *playSlider = [[UISlider alloc] init];
        _playSlider = playSlider;
        //    生成透明图片
        CGSize s=CGSizeMake(1, 1);
        UIGraphicsBeginImageContextWithOptions(s, 0, [UIScreen mainScreen].scale);
        UIRectFill(CGRectMake(0, 0, 1, 1));
        UIImage *img=UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //    添加图片，大按钮就去掉了，这个img置为空是去不掉的
        [playSlider setThumbImage:img forState:UIControlStateNormal];
        playSlider.minimumTrackTintColor = [UIColor redColor];

        [self addSubview:playSlider];
        [playSlider mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(self);
            make.height.offset(1);
        }];
        
        
        //init
        self.hidden = YES;
        [self refreshUIWithStatus:_LCPlayer.kstatus];

    }
    return self;
}
// 安装通知
- (void)setupNotifications {
    // 1. 安装播放状态发生变化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerStatusDidChangedNotification:) name:LCMusicPlayerStatusDidChangedNotification object:_LCPlayer];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"alpha" object:nil];
    // 2. 播放歌曲发生变化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerPlayingSongDidChangedNotification:) name:LCMusicPlayerPlayingSongDidChangedNotification object:_LCPlayer];

    // 3. 安装歌曲进度发生变化后回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerCurrentTimeDidChangedNotification:) name:LCMusicPlayerCurrentTimeDidChangedNotification object:_LCPlayer];

}
- (void)dealloc
{
    [self teardownNotifications];
}
// 卸载通知
- (void)teardownNotifications {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)receiveNotification:(NSNotification *)notification{
    if (_isOpenHiddenPanDuan == NO) {
        return;
    }
    
    if ([self.title isEqualToString:@"1"]) {
        self.hidden = NO;
    }else{
        self.hidden = !self.hidden;
    }
    
//    self.alpha = !self.alpha;
//    if (self.hidden) {
//        NSLog(@"已隐藏");
//    }else{
//        NSLog(@"未隐藏");
//    }
}
- (void)musicPlayerStatusDidChangedNotification:(NSNotification *)notification {
    // 获取当前播放状态
    LCMusicPlayerStatus status = [notification.userInfo[kMusicPlayerStatus] integerValue];
    
    // 绑定播放状态和界面之间的关系
    [self refreshUIWithStatus:status];
}

- (void)musicPlayerPlayingSongDidChangedNotification:(NSNotification *)notification {
    JKSongsMessStatus *playingSong = notification.userInfo[kMusicPlayerPlayingSong];
    _titleLabel.text = playingSong.title;
    _albumLabel.text =
    playingSong.singerName;//旧歌手字段
    if (playingSong.artist_name.length > 0) {
        _albumLabel.text =
        playingSong.artist_name;//新歌手字段
    }
    NSURL *url = [NSURL URLWithString:playingSong.image];
    if (playingSong.image != nil) {
//        url = [NSURL URLWithString:playingSong.image300];
        
    }
    [_titleImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"play_icon"]];
    NSArray<UILabel *> *array = @[_titleLabel,_albumLabel];
    for (NSInteger i = 0; i < array.count; i++) {
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionLiebiaoClick)];
        array[i].userInteractionEnabled = YES;
        [array[i] addGestureRecognizer:tapGestureRecognizer];
    }
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(actionLiebiaoClick)];
    _titleImageView.userInteractionEnabled = YES;
    [_titleImageView addGestureRecognizer:tapGestureRecognizer];

}


// 播放状态和界面之间的关系
- (void)refreshUIWithStatus:(LCMusicPlayerStatus)status {
    //设置是否可以交互
//    self.userInteractionEnabled = status == LCMusicPlayerStatusPlaying;
    // 告诉播放按钮状态和播放器内部的状态之间的关系
    self.playOrPauseButton.selected = status == LCMusicPlayerStatusPlaying;
}

#pragma mark - action方法 -
- (IBAction)actionNext:(id)sender {
    _playSlider.value = 0;
    [_LCPlayer next];
}

- (IBAction)actionLiebiao:(id)sender {
    
    if (_LCPlayer.songs.count > 0) {
        [self example7];
    }
}

- (void)example7 {
    zhWallView *wallView = [self wallView];
    wallView.didClickFooter = ^(zhWallView * _Nonnull sheetView) {
        [self.zh_popupController dismiss];
    };
    
    self.zh_popupController = [zhPopupController new];
    self.zh_popupController.layoutType = zhPopupLayoutTypeBottom;
    [self.zh_popupController presentContentView:wallView];
}
- (zhWallView *)wallView {
    CGRect rect = CGRectMake(100, 100, [UIScreen mainScreen].bounds.size.width, 300);
    zhWallView *wallView = [[zhWallView alloc] initWithFrame:rect];
    wallView.wallHeaderLabel.text = [NSString stringWithFormat:@"清空"];
    wallView.wallFooterLabel.text = @"关闭";
    wallView.models = @[wallView.wallHeaderLabel.text, wallView.wallFooterLabel.text];
    [wallView autoAdjustFitHeight];
    return wallView;
}

- (NSString *)randomOrSinglePlayStr{
    NSString *str;
    if (_LCPlayer.listStatus == LCMusicListStatusAllCycle) {
        str = @"循环播放";
    } else if(_LCPlayer.listStatus == LCMusicListStatusRandom){
        str = @"随机播放";
    }else if(_LCPlayer.listStatus == LCMusicListStatusSingleCycle){
        str = @"单曲播放";
    }
    return str;
}

/**
 名称 点击 模态播放控制器页面和消失
 */
- (void)actionLiebiaoClick {
    
    if(self.didPushPlayPage != nil) {
        self.didPushPlayPage();
    }
    //    if(self.contentView != nil) {
    //        [self.contentView removeFromSuperview];
    //        self.contentView = nil;
    //    }

    [[NSNotificationCenter defaultCenter] postNotificationName:@"PUSHPLAYPAGE" object:self];
}

- (IBAction)actionTap:(id)sender {
   NSLog(@" __func__ = %s",  __func__);
//
}


#pragma mark - 公共方法 -
/**
 在拖拽的窗体中显示某个视图
 
 @param view 外部传入的视图
 @param closeBlock 关闭回调函数
 */
- (void)show:(UIView *)view didCloseBlock:(void(^)(void))closeBlock {
    
    UIView *view1 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor whiteColor];
    view1.alpha = 0.9;

    self.contentView = view1;
    self.didCloseBlock = closeBlock;
    [self insertSubview:self.contentView atIndex:0];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    self.hidden = YES;
    
}

- (void)musicPlayerCurrentTimeDidChangedNotification:(NSNotification *)notification {
    NSTimeInterval currentTime = [notification.userInfo[kCurrentTime] floatValue];
    NSTimeInterval totalTime = [notification.userInfo[kTotalTime] floatValue];
    _playSlider.value = currentTime / totalTime;
}

- (IBAction)actionPlayOrPause:(UIButton *)sender {
    // 通过按钮的状态来触发播放状态
    if(_LCPlayer.kstatus == LCMusicPlayerStatusPlaying) {
        [_LCPlayer pause];
    } else {
        [_LCPlayer play];
    }
}

@end
